package com.lanmao.blog.controller;


import com.lanmao.blog.entity.User;
import com.lanmao.blog.service.UserService;
import com.lanmao.blog.utils.BLOG_CONSTANT;
import com.lanmao.blog.utils.R;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lanmao
 * @since 2022-03-13
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    UserService userService;

    /**
     * 更新个人信息
     * @param user
     * @return
     */
    @PutMapping("/updateinfo")
    public R updateinfo(@RequestBody User user){
        User user1=userService.update(user);
        return R.ok().message("更新成功").data("data",user1);
    }

    /**
     * 发送验证码
     * @param phone
     * @return
     */
    @PostMapping("/sendcode")
    public R sendcode(@Param("phone") String phone){
        if(StringUtils.isEmpty(phone)){//防止空攻击
            return R.error().message("请输入手机号");
        }
        String rediscode = stringRedisTemplate.opsForValue().get(BLOG_CONSTANT.PHONE_CACHE + phone);
        if (!StringUtils.isEmpty(rediscode)){//判断这个手机号60秒内是否发送过验证码
            Long time = Long.parseLong(rediscode.split("_")[1]);
            if (System.currentTimeMillis() - time <60000){//接口防刷
                return R.error().message("验证码获取频率太高，稍后重试");
            }
        }
        String code = UUID.randomUUID().toString().substring(0, 4);
        String code1=code+"_"+System.currentTimeMillis();//要判断用户是否60秒内已经发送过验证码，所以加一个时间蹉
        stringRedisTemplate.opsForValue().set(BLOG_CONSTANT.PHONE_CACHE + phone,code1,5, TimeUnit.MINUTES);//验证码有效期设置为5分钟
        userService.sendcode(phone,code);
        return R.ok();
    }



}

